package com.M10.BE.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.M10.BE.R;
import com.M10.BE.adapter.InveCheckListAdapter;
import com.M10.BE.adapter.InveUnCheckListAdapter;
import com.M10.BE.adapter.NullStringToEmptyAdapterFactory;
import com.M10.BE.entity.NAsset;
import com.M10.BE.file.FileService;
import com.M10.BE.inventory.DoInventoryActivity;
import com.fn.useries.UHFApplication;
import com.fn.useries.model.Inventory;
import com.fn.useries.utils.PreferenceUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * @author Lenovo
 * @desc
 * @time 2018/3/6 9:53
 */

/**
 * 待盘点
 */
public class WaitInveFragment extends Fragment {
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.srl_list)
    SmartRefreshLayout srlList;
    Unbinder unbinder;
    @BindView(R.id.tv_frg_list_title)
    TextView tvFrgListTitle;
    @BindView(R.id.empty)
    LinearLayout empty;
    @BindView(R.id.ll_frg_content)
    LinearLayout ll_frg_content;
    @BindView(R.id.iv_has_inve)
    ImageView iv_has_inve;
    private Gson gson;
    private int pageNumber = 1;
    private InveUnCheckListAdapter adapter;
    private ArrayList<Inventory> assetArrayList = new ArrayList<>();

    public static WaitInveFragment newInstance() {
        WaitInveFragment fragment = new WaitInveFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showDialog();
    }

    private void showDialog() {
        if (hasInve()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setMessage("你有一个未完成盘点的任务，是否进入继续操作");
            builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(getActivity(), DoInventoryActivity.class);
                    startActivity(intent);
                }
            });
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (hasInve()) {
            iv_has_inve.setClickable(true);
        } else {
            iv_has_inve.setClickable(false);
        }
    }

    @OnClick(R.id.iv_has_inve)
    public void onImageViewClicked() {
        showDialog();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frg_inve_list, container, false);
        unbinder = ButterKnife.bind(this, view);
        gson = new GsonBuilder().serializeNulls().
                registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
        adapter = new InveUnCheckListAdapter(assetArrayList, getActivity());
        rvList.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvList.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        rvList.setAdapter(adapter);
        srlList.setEnableHeaderTranslationContent(false);
        srlList.setRefreshHeader(new MaterialHeader(getActivity()));
        srlList.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                ((View) refreshlayout).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        pageNumber = 1;
                        pullUpRefresh("", "", "", pageNumber);
                    }
                }, 2000);
//                new ReadUncheckInventory().execute();
            }
        });
        srlList.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                ((View) refreshlayout).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadMore("", "", "", pageNumber);
                    }
                }, 2000);

            }
        });
        srlList.autoRefresh();
        return view;
    }

    private boolean hasInve() {
        String a = PreferenceUtils.readString(getContext(), "assets", "downinventory");
        if (a != null) {
            return true;
        } else {
            return false;
        }
    }

    public void pullUpRefresh(String name, String code, String useOrg, int pageCurrent) {
        pageNumber = 1;
        OkGo.<String>get(UHFApplication.BASE_HEAD + "judge/APPlist")
                .tag(this)
                .params("name", "")
                .params("code", "")
                .params("useOrg", "")
                .params("pageSize", "12")
                .params("pageCurrent", pageCurrent)
                .params("proState", "1")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {

                            JSONObject ob = new JSONObject(response.body());
                            String errcode = ob.getString("statusCode");
                            String msg = ob.getString("msg");
                            if ("0".equals(errcode)) {
                                String result = ob.getString("result");
                                JSONObject re_json = new JSONObject(result);
                                JSONArray pg = re_json.optJSONArray("list");
                                if (re_json.getJSONArray("list") != null) {
                                    assetArrayList.clear();
                                    if (pg.length() > 0) {
                                        for (int i = 0; i < pg.length(); i++) {
                                            assetArrayList.add(gson.fromJson(pg.get(i).toString(), Inventory.class));
                                        }
                                        adapter.notifyDataSetChanged();
                                        srlList.finishRefresh();

                                        if (re_json.optInt("totalPage") > pageNumber) {
                                            pageNumber++;

                                            srlList.setLoadmoreFinished(false);
//                                        srlList.autoLoadmore();
                                            Log.e("xx", "onSuccess: " + "yyyyyyyyy");
                                        } else {
                                            //禁止加载更多
                                            Log.e("xx", "onSuccess: " + "xxxxxxxxxx");
                                            srlList.setLoadmoreFinished(true);
                                        }
                                    } else {
//                                    adapter.notifyDataSetChanged();
                                        srlList.finishRefresh();
                                    }
                                } else {
                                    empty.setVisibility(View.VISIBLE);
                                    ll_frg_content.setVisibility(View.GONE);
                                    srlList.finishRefresh();
                                    //查询失败
                                }
                            } else {

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            srlList.finishRefresh();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        empty.setVisibility(View.VISIBLE);
                        ll_frg_content.setVisibility(View.GONE);
                        srlList.finishRefresh();
                    }
                });
    }

    private void loadMore(String name, String code, String useOrg, int pageCurrent) {
        OkGo.<String>get(UHFApplication.BASE_HEAD + "judge/APPlist")
                .tag(this)
                .params("name", name)
                .params("code", code)
                .params("useOrg", useOrg)
                .params("pageSize", "12")
                .params("pageCurrent", pageCurrent)
                .params("proState", "1")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {

                            JSONObject object = new JSONObject(response.body());
                            if (object.optInt("status") == 1) {


                                JSONArray pg = object.optJSONArray("pg");
                                if (pg.length() > 0) {
                                    for (int i = 0; i < pg.length(); i++) {
                                        assetArrayList.add(gson.fromJson(pg.get(i).toString(), Inventory.class));
                                    }
                                    adapter.notifyDataSetChanged();
                                    srlList.finishLoadmore();
                                    if (object.optInt("totalPage") > pageNumber) {
                                        pageNumber++;
                                        srlList.setLoadmoreFinished(false);
                                        srlList.autoLoadmore();
                                    } else {
                                        //禁止加载更多
                                        srlList.setLoadmoreFinished(true);
                                    }
                                } else {
//                                    adapter.notifyDataSetChanged();
                                    srlList.finishLoadmore();
                                }
                            } else {
                                //查询失败
                                empty.setVisibility(View.VISIBLE);
                                ll_frg_content.setVisibility(View.GONE);
                                srlList.finishLoadmore();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            srlList.finishLoadmore();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        empty.setVisibility(View.VISIBLE);
                        ll_frg_content.setVisibility(View.GONE);
                        srlList.finishLoadmore();
                    }
                });
    }

    private class ReadUncheckInventory extends AsyncTask<Void, Void, List<Inventory>> {

        private List<Inventory> results = new ArrayList<>();

        @Override
        protected List<Inventory> doInBackground(Void... voids) {
            List<String> fileLines = FileService.readFile();
            try {
                if (fileLines.size() > 0) {
                    for (int i = 0; i < fileLines.size(); i++) {
                        results.add(gson.fromJson(fileLines.get(i).toString(), Inventory.class));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
//        else {
//            //查询失败
//            empty.setVisibility(View.VISIBLE);
//            ll_frg_content.setVisibility(View.GONE);
//            srlList.finishLoadmore();
//        }
            return results;
        }

        @Override
        protected void onPostExecute(List<Inventory> inventories) {
            super.onPostExecute(inventories);
            if (results != null && results.size() > 0) {
                assetArrayList.clear();
                assetArrayList.addAll(results);
                adapter.notifyDataSetChanged();
                srlList.finishLoadmore();
                if (results.size() > pageNumber) {
                    pageNumber++;
                    srlList.setLoadmoreFinished(false);
                    srlList.autoLoadmore();
                } else {
                    //禁止加载更多
                    srlList.setLoadmoreFinished(true);
                }
                srlList.finishRefresh();
            } else {
//                                    adapter.notifyDataSetChanged();
                srlList.finishLoadmore();
                empty.setVisibility(View.VISIBLE);
                ll_frg_content.setVisibility(View.GONE);
                srlList.finishRefresh();
            }


        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.tv_frg_list_title)
    public void onViewClicked() {
        Toast.makeText(getActivity(), "search", Toast.LENGTH_SHORT).show();
    }
}
